import { Scene } from 'phaser';

export class Game extends Scene {
    platforms: Phaser.Physics.Arcade.StaticGroup;

    player: Phaser.Physics.Arcade.Sprite;

    cursor: Phaser.Types.Input.Keyboard.CursorKeys;

    stars: Phaser.Physics.Arcade.Group;

    score: number = 0;

    bombs: Phaser.Physics.Arcade.Group;

    scoreText: Phaser.GameObjects.Text;

    gameOVerText: Phaser.GameObjects.Text;

    restartText: Phaser.GameObjects.Text;

    keyboard: Phaser.Input.Keyboard.KeyboardPlugin;

    particle: Phaser.GameObjects.Particles.ParticleEmitter;

    gameOver: boolean = false;
    constructor() {
        super('Game');
    }

    preload() {
        this.load.image('sky', 'assets/sky.png');
        this.load.image('ground', 'assets/platform.png');
        this.load.image('star', 'assets/star.png');
        this.load.image('bomb', 'assets/bomb.png');
        this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
    }

    create() {
        this.input.keyboard?.addListener('keydown', (event: KeyboardEvent) => {
            if (event.key === 'r') {
                this.scene.restart();
            }
        })
        this.add.image(400, 300, 'sky');

        this.platforms = this.physics.add.staticGroup();

        this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
        this.platforms.create(600, 400, 'ground');
        this.platforms.create(50, 250, 'ground');
        this.platforms.create(750, 220, 'ground');
        this.player = this.physics.add.sprite(100, 450, 'dude');
        this.player.setBounce(0.2);
        this.player.setCollideWorldBounds(true);

        this.particle = this.add.particles(0, 0, 'star', {
            speed: 100,
            lifespan: 2000,
            gravityY: 0,
            scale: { start: 0.25, end: 1 },
            alpha: { start: 1, end: 0 },
            angle: { min: 0, max: 360 },
            rotate: { start: 0, end: 360, random: true },
            quantity: 100,
            frequency: -1
        });

        this.anims.create({
            key: 'left',
            frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
            frameRate: 10,
            repeat: -1
        })

        this.anims.create({
            key: 'turn',
            frames: [{ key: 'dude', frame: 4 }],
            frameRate: 20
        })

        this.anims.create({
            key: 'right',
            frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
            frameRate: 10,
            repeat: -1
        })

        this.physics.add.collider(this.player, this.platforms);
        this.player?.body?.setGravityY(300);

        this.cursor = this.input.keyboard.createCursorKeys();

        this.stars = this.physics.add.group({
            key: 'star',
            repeat: 11,
            setXY: { x: 12, y: 0, stepX: 70 },
            bounceY: Phaser.Math.FloatBetween(0.4, 0.8)
        })

        // this.stars.children.iterate((child: any) => {

        //     return child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
        // })
        const hitBomb = (player: any, bomb: any) => {
            this.physics.pause();
            player.setTint(0xff0000);
            player.anims.play('turn');
            this.gameOver = true
            this.gameOVerText = this.add.text(400, 300, 'Game Over', {
                fontSize: '64px',
                color: '#000'
            });
            this.restartText = this.add.text(400, 400, 'Press R to Restart', {
                fontSize: '32px',
                color: '#000'
            });
            this.restartText.setOrigin(0.5, 0.5);
            this.restartText.setAlpha(0);
            this.tweens.add({
                targets: this.restartText,
                alpha: 1,
                duration: 1000,
                ease: 'Power1',
                yoyo: true,
                repeat: -1
            });
            this.gameOVerText.setOrigin(0.5, 0.5);
            this.gameOVerText.setAlpha(0);
            this.tweens.add({
                targets: this.gameOVerText,
                alpha: 1,
                duration: 1000,
                ease: 'Power2',
                yoyo: true,
                repeat: -1
            });
            return true;
        }

        const collectStar = (player: any, star: any) => {
            this.particle.emitParticleAt(star.x, star.y, 1000);
            star.disableBody(true, true);
            // if (this.stars.countActive(true) === 0) {
            //     this.stars.children.iterate((child: any) => {
            //         child.enableBody(true, child.x, 0, true, true);
            //     })
            // }
            this.score += 10;
            this.scoreText.setText('Score: ' + this.score);

            if (this.stars.countActive(true) === 0) {
                this.stars.children.iterate((child: any) => {
                    return child.enableBody(true, child.x, 0, true, true);
                })

                var x = (this.player.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);

                var bomb = this.bombs.create(x, 16, 'bomb');
                bomb.setBounce(1);
                bomb.setCollideWorldBounds(true);
                bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);


                return true;
            }






        }

        this.physics.add.collider(this.stars, this.platforms);

        this.physics.add.overlap(this.player, this.stars, collectStar, undefined, this)

        this.scoreText = this.add.text(16, 16, 'score: 0', {
            fontSize: '32px',
            color: '#000'
        });

        this.bombs = this.physics.add.group();

        this.physics.add.collider(this.bombs, this.platforms);

        this.physics.add.overlap(this.player, this.bombs, hitBomb, undefined, this)
    }

    update(): void {
        if (this.cursor?.left.isDown) {
            this.player?.setVelocityX(-160);
            this.player?.anims.play('left', true);
        }
        else if (this.cursor?.right.isDown) {
            this.player?.setVelocityX(160);
            this.player?.anims.play('right', true);
        }
        else {
            this.player?.setVelocityX(0);
            this.player?.anims.play('turn');
        }

        if (this.cursor?.up.isDown && this.player.body?.touching.down) {
            this.player.setVelocityY(-500);
        }
    }

}
